package com.young.design.pattern.prototype.deepclone;

import java.io.*;

public class DeepProtoType implements Cloneable, Serializable {
    private String name;
    private DeepCloneableTarget deepCloneableTarget;

    public DeepProtoType() {
        deepCloneableTarget= new DeepCloneableTarget();
    }

    @Override
    protected DeepProtoType clone() throws CloneNotSupportedException {
        DeepProtoType deepProtoType = (DeepProtoType)super.clone();
        DeepCloneableTarget deepCloneableTarget = deepProtoType.getDeepCloneableTarget();
        DeepCloneableTarget deepCloneableTargetClone = deepCloneableTarget.clone();
        deepProtoType.setDeepCloneableTarget(deepCloneableTargetClone);

        return deepProtoType;
    }


    public DeepProtoType deepClone(){
        byte[] bytes = new byte[1024];

        try( ByteArrayOutputStream bos=new ByteArrayOutputStream();
             ObjectOutputStream oos=new ObjectOutputStream(bos);
             ) {
            oos.writeObject(this);
            ByteArrayInputStream bis=new ByteArrayInputStream(bos.toByteArray());
            ObjectInputStream ois=new ObjectInputStream(bis);

            DeepProtoType cloneResult =(DeepProtoType) ois.readObject();
            return cloneResult;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public DeepCloneableTarget getDeepCloneableTarget() {
        return deepCloneableTarget;
    }

    public void setDeepCloneableTarget(DeepCloneableTarget deepCloneableTarget) {
        this.deepCloneableTarget = deepCloneableTarget;
    }
}
